package com.book.modules.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.book.common.api.entity.CurrentUser;
import com.book.modules.core.entity.DataEntity;
import com.book.modules.helper.CurrentUserHelper;
import com.book.oauth.server.user.vo.CurrentUserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Description： 自定义自动填充字段处理器
 * @Author： leo.xiong
 * @CreateDate： 2019/10/22 17:16
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private CurrentUserHelper currentUserHelper;

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createDate", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateDate", Date.class, new Date());
        this.strictInsertFill(metaObject, "status", String.class, DataEntity.STATUS_NORMAL);
        CurrentUser currentUser = currentUserHelper.getCurrentUser();
        if (currentUser != null) {
            this.strictInsertFill(metaObject, "createBy", String.class, currentUser.getId());
            this.strictInsertFill(metaObject, "updateBy", String.class, currentUser.getId());
            this.strictInsertFill(metaObject, "createName", String.class, currentUser.getUsername());
            this.strictInsertFill(metaObject, "updateName", String.class, currentUser.getUsername());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateDate", Date.class, new Date());
        CurrentUser currentUser = currentUserHelper.getCurrentUser();
        if (currentUser != null) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, currentUser.getId());
            this.strictUpdateFill(metaObject, "updateName", String.class, currentUser.getUsername());
        }
    }
}
